<template>
    <NDialog v-model:show="showSuccessDialog" :closable="false">
      <NCard title="{{ $t('password.successTitle') }}" class="max-w-md">
        <NCardContent class="text-center">
          <p class="text-gray-600 dark:text-gray-300">{{ successMessage }}</p>
        </NCardContent>
        <NCardFooter class="flex justify-center">
          <NButton @click="handleDialogConfirm">{{ $t('btn.confirm') }}</NButton>
        </NCardFooter>
      </NCard>
    </NDialog>
    <div class="flex justify-center px-4 sm:px-6 lg:px-8 py-10 space-y-12">
      <!-- 用户信息 -->
      <NCard class="shadow-none xl:w-2/5 lg:w-3/4 md:w-1/2 w-full" card="~">
        <NCardHeader>
          <div class="flex flex-col gap-1">
            <NCardTitle class="text-xl font-semibold">{{ $t('password.title') }}</NCardTitle>
          </div>
        </NCardHeader>
        <hr class="my-8 border-gray-200" />
        <NCardContent class="space-y-6">
            <form @submit.prevent="onValidating()">
            <input name="hidden" autocomplete="false" style="display: none" />
            <NFormField
                name="currentPassword"
                :label="`${$t('password.currentPassword')}*`"
                :description="$t('password.currentDescription')"
                :status="errs['currentPassword'] ? 'error' : undefined"
                :message="errs['currentPassword']"
              >
                <NInput
                  type="password"
                  class="w-full focus:outline-none border py-3 appearance-none h-12 block px-3 rounded-xl sm:text-sm"
                  :placeholder="$t('password.currentPassword')"
                  v-model="form.currentPassword"
                  autofocus
                />
              </NFormField>
            <NFormField
                name="newPassword"
                :label="`${$t('password.newPassword')}*`"
                :description="$t('password.newDescription')"
                :status="errs['newPassword'] ? 'error' : undefined"
                :message="errs['newPassword']"
              >
                <NInput
                  type="password"
                  class="w-full focus:outline-none border py-3 appearance-none h-12 block px-3 rounded-xl sm:text-sm"
                  :placeholder="$t('password.newPassword')"
                  v-model="form.newPassword"
                />
              </NFormField>
            <NFormField
                name="confirmPassword"
                :label="`${$t('password.confirmPassword')}*`"
                :description="$t('password.confirmDescription')"
                :status="errs['confirmPassword'] ? 'error' : undefined"
                :message="errs['confirmPassword']"
              >
                <NInput
                  type="password"
                  class="w-full focus:outline-none border py-3 appearance-none h-12 block px-3 rounded-xl sm:text-sm"
                  :placeholder="$t('password.confirmPassword')"
                  v-model="form.confirmPassword"
                />
              </NFormField>
              <NAlert icon alert="soft-error" v-if="errs['innerError']">
                <label class="inline-flex items-center">
                  <i class="fa-solid fa-triangle-exclamation pr-2"></i>
                  {{ $t(errs['innerError']) }}
                </label>
              </NAlert>
          <NButton class="mt-4" 
            type="submit"
            :loading="status=='pending' && pending"
          >{{ $t('password.changePassword') }}</NButton>
        </form>
        </NCardContent>
      </NCard>
    </div>
  </template>
  
<script setup>
import { useRouter } from 'nuxt/app'
import { useForm } from 'vee-validate'
import { toTypedSchema } from '@vee-validate/zod'
import { UserPasswordChangeSchema } from '@/schema/user.schema'

definePageMeta({ layout: 'secure' })

const errs = ref({})
const showSuccessDialog = ref(false)
const successMessage = ref('')
const form = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const router = useRouter()

// API调用配置
const { data, error, execute, pending, status } = await useFetch('/api/secure/user/password', {
  method: 'PUT',
  immediate: false,
  body: form
})

// 表单验证设置
const { handleSubmit, validate, errors } = useForm({
  validationSchema: toTypedSchema(UserPasswordChangeSchema())
})

// 提交处理函数
const onSubmit = handleSubmit(async (values) => {
  await execute()
})

// 验证并提交表单
async function onValidating() {
  await validate()
  const firstErrorField = Object.keys(errors.value)[0]
  if (firstErrorField) {
    const firstErrorFieldElement = document.querySelector(`[name=${firstErrorField}]`)
    if (firstErrorFieldElement) {
      firstErrorFieldElement.focus()
      firstErrorFieldElement?.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  }
  await onSubmit()
}

// 监听请求状态变化
watch(status, async (newVal) => {
  if (newVal === 'success') {
    successMessage.value = data.value?.statusMessage || $t('password.updateSuccess')
    showSuccessDialog.value = true
  }
})

// 处理对话框确认按钮点击
const handleDialogConfirm = () => {
  showSuccessDialog.value = false
  router.push('/secure/dashboard')
}

watch(error, (newVal) => {
  if (newVal?.data?.error) {
    if (newVal?.data?.statusCode === 400) {
      let _errors = []
      for (var issue of newVal?.data?.data) {
        _errors[issue.path[0]] = issue.message
      }
      errs.value = _errors
      return
    }
    const _err = (newVal?.data?.statusCode === 500)?'innerError':newVal?.data?.message
    errs.value = { innerError: _err }
  }
})
</script>